package es.cea.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/ListadoLibros")
public class ListadoLibros extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter pw=response.getWriter();
		pw.print("<html><head></head><body>");
		pw.print("<h1 align='center'>Listado de libros</h1><hr><br>");
		pw.print("<table border='1' align='centre'> ");
		pw.print("<tr><th>Titulo</th><th>Fecha</th><th>Autor</th></tr>");
		
		ArrayList<Libro> libros = new ArrayList<Libro>();
    	Libro l =new Libro();
    	
    	try  
    	{  
    	Class.forName("com.mysql.jdbc.Driver");  
    	Connection conexion = DriverManager.getConnection ("jdbc:mysql://localhost/libreria","root", "root");  
    	Statement s = conexion.createStatement();  
    	ResultSet rs = s.executeQuery("select * from libros");
    	
    		while(rs.next()){
    			System.out.println(rs.getString(1)+ ", " +rs.getString(2)+ ", " +rs.getString(3));
        	
    			l.setId(rs.getInt(1)); l.setTitulo(rs.getString(2)); l.setFecha(rs.getDate(3));
    			libros.add(l);  	 	    	 	
    	 		pw.print("<tr><td>"+l.getTitulo()+"</td><td>"+l.getFecha()+"</td><td>"+l.getAutor()+"</td>");
    	 		pw.print("<td>&nbsp;<a href='Detalle?id="+l.getId()+"&titulo="+l.getTitulo()+"&fecha="+ l.getFecha()+"&autor="+ l.getAutor() +" '>Detalles</a></td> ");
    	 		pw.print("<td><a href='EditarLibro?id="+l.getId()+"&titulo="+l.getTitulo()+"&fecha="+ l.getFecha()+"&autor="+ l.getAutor() +" '>Editar</a></td></tr>");
    		}
    		s.close();
    	
    	}
    	catch (Exception e){  
    	   e.printStackTrace();  
    	}  
    	
    	pw.print("</table>");
    	pw.println("</html></body>");
    	pw.close();
    

		
	}
	}
	

